let express = require("express")
let bodyParser = require("body-parser")
var jwt = require("jsonwebtoken");
let app = express()

var uE = bodyParser.urlencoded({ extended: false })
// app.use(function(req,res,next){
//     res.header('Access-Control-Allow-Origin', '*');

//     res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');

//     res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE,OPTIONS');
//     next();
// })

//axios学习测试接口
app.get("/userlist/getlink", (req, res) => {

    res.send({ msg: "我是后台返回的get数据", data: { name:"么么哒"} })
})

// 模拟get请求接收参数
app.get("/userlist/get", (req, res) => {
    console.log(req.query.name)
    res.send({ msg: "我是后台返回的get数据", data: { name: "你发送给后台的name" + req.query.name } })
})

// 模拟post请求接受参数
app.post("/userlist/post", uE, (req, res) => {
    console.log(req.body.name)
    res.send({ msg: "我是后台返回的post数据", data: { name: "你发送给后台的name" + req.body.name } })
})

// 模拟delete请求接收参数
app.delete("/userlist/delete", (req, res) => {
    console.log(req.query.name)
    res.send({ msg: "我是后台返回的delete数据", data: { name: "你发送给后台的name" + req.query.name } })
})
// 模拟put请求接收参数
app.put("/userlist/put", uE, (req, res) => {
    console.log(req.body)
    res.send({ msg: "我是后台返回的put数据", data: { name: "你发送给后台的name" + req.body.name } })
})

// 登录模拟返回token

app.post("/userlist/logintoken", uE, (req, res) => {
    console.log(req.body.uname)
    console.log(req.body.upwd)
    if (req.body.uname === "admin" && req.body.upwd === "admin123") {
        // 生成token
        // 产生token

        // jwt.sign(数据,随便一点内容，加密的密文(越乱越好))

        var data = {
            uname: "xixi",
            userid: "1"
        }
        var mi = "asdkaldkjadlkjasdkajxcoviu"//加密的密文(越乱越好)
        var token = jwt.sign(data, mi);
        res.send({ msg: "登录成功", data: { loginok: 1, token } })
    } else {
        res.send({ msg: "登录失败", data: { loginok: 0, token: null } })
    }

})


// token验证
app.get("/userlist/routertoken", (req, res) => {
    console.log("aa",req.headers.usertoken)
    
    // console.log(res)

    // 验证token是否正确
    // jwt.verify(验证的token,加密的密文，回调)
    if(req.headers.usertoken!="null"){
       
        var mi = "asdkaldkjadlkjasdkajxcoviu"//加密的密文(越乱越好)
        jwt.verify(req.headers.usertoken, mi, function (err, data) {
            console.log(err);//正确就是null
            console.log(data);
            if (data.userid == "1") {
                res.send({ msg: "用户登录过", data: { routerok: 1 } })
            } else {
                res.send({ msg: "用户没有登录过", data: { routerok: 0 } })
            }
    
        })
    }else{
        res.send({ msg: "用户没有登录过", data: { routerok: 0 } })
    }
  


})

app.listen(8888)
